package com.foreknow.elmboot.service.impl;

import com.foreknow.elmboot.mapper.CartMapper;
import com.foreknow.elmboot.mapper.OrderdetailetMapper;
import com.foreknow.elmboot.mapper.OrdersMapper;
import com.foreknow.elmboot.po.Cart;
import com.foreknow.elmboot.po.Orderdetailet;
import com.foreknow.elmboot.po.Orders;
import com.foreknow.elmboot.service.OrdersService;
import com.foreknow.elmboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderdetailetMapper orderdetailetMapper;

    @Override
    @Transactional
    public int screateOrders(Orders orders) {


        Cart cart = new Cart();
        cart.setUserId(orders.getUserId());
        cart.setBusinessId(orders.getBusinessId());
        List<Cart> cartList = cartMapper.dlistCart(cart);


        orders.setOrderDate(CommonUtil.getCurrentDate());
        ordersMapper.dcreateOrders(orders);

        List<Orderdetailet> list = new ArrayList<>();
        for (int a = 0;a < cartList.size();a++){
            Orderdetailet orderdetailet = new Orderdetailet();
            orderdetailet.setOrderId(orders.getOrderId());
            orderdetailet.setFoodId(cartList.get(a).getFoodId());
            orderdetailet.setQuantity(cartList.get(a).getQuantity());
            list.add(orderdetailet);
        }
        orderdetailetMapper.daoinsetorderdetailet(list);


        cartMapper.dremoveCart(cart);
        return orders.getOrderId();
    }

    @Override
    public Orders sgetOrdersById(Orders orders) {

            return ordersMapper.dgetOrdersById(orders);
    }

    @Override
    public List<Orders> slistOrdersByUserId(Orders orders) {
        return ordersMapper.dlistOrdersByUserId(orders);
    }
}
